package com.tfswx.jcyw.sqlmodel.gic.operators;

import com.alibaba.fastjson.JSON;
import com.tfswx.jcyw.sqlmodel.api.Operator;
import com.tfswx.jcyw.sqlmodel.api.bean.Node;
import com.tfswx.jcyw.sqlmodel.api.bean.jdpz.JoinJdpz;
import com.tfswx.jcyw.sqlmodel.api.bean.jdpz.ZdItem;
import com.tfswx.jcyw.sqlmodel.api.bean.table.*;
import com.tfswx.jcyw.sqlmodel.api.bean.table.expression.Column;
import com.tfswx.jcyw.sqlmodel.api.bean.table.expression.WhereItem;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 张述江
 * @date 2023/9/7
 */
public class DefaultJoinOperator implements Operator {
    @Override
    public String getName() {
        return "连接";
    }

    @Override
    public Select operate(Node node, List<Select> pResultList) {
        System.out.println("执行了" + getName() + "操作");
        JoinJdpz joinJdpz = JSON.parseObject(node.getJdpz(), JoinJdpz.class);
        String zjdbm = joinJdpz.getZjdbm();
        Select zjdSelect = pResultList.get(0);
        Select cjdSelect = pResultList.get(1);
        if (!zjdbm.equals(zjdSelect.getAlias().getName())) {
            zjdSelect = cjdSelect;
            cjdSelect = pResultList.get(0);
        }

        PlainSelect select = new PlainSelect(new ParenthesedSelect(zjdSelect));
        List<Join> joins = new ArrayList<>();
        WhereItem whereItem = WhereItem.parse(joinJdpz.getLjbdsList());
        Join join = new Join(Join.JoinType.LEFT, new ParenthesedSelect(cjdSelect), whereItem);

        joins.add(join);
        select.setJoins(joins);

        for (ZdItem zdItem : joinJdpz.getZdList()) {
            select.addSelectItem(new SelectItem(new Column(zdItem.getZdbds().toString()), new Alias(zdItem.getZdbm())));
        }

        return select;
    }
}
